<?php
namespace Home\Controller;

use Think\Controller;
use Think\Log;

class PayController extends Controller
{

    public function __construct()
    {
        vendor('Weixinpay.WxPayApi');
    }

    public function index()
    {
        $openid = I('openId');
        $radio  = I('radio');
        $tempId = intval(I('cardId')); //模板id
        if ($radio == 1) {//payType 1=>全部支付 2=>选择模板付款
            $totalFee = 2;
            $payType  = 2;
        } elseif ($radio == 2) {
            $totalFee = 6.6;
            $payType  = 1;
        }

        $body = '拜年卡';
        //初始化值对象
        $input = new \WxPayUnifiedOrder();
        //档提及的参数规范：商家名称-销售商品类目
        $input->SetBody($body);
        //生成订单号
        $tradeNo = buildTradeNo();
        Log::write('订单号：' . $tradeNo);
        //订单号应该是由小程序端传给服务端的，在用户下单时即生成，demo中取值是一个生成的时间戳
        $input->SetOut_trade_no($tradeNo);
        //费用1，即1分钱
        $input->SetTotal_fee($totalFee * 100);
        $input->SetNotify_url(C('pay_config')['app_notify_url']); //需要自己写的notify.php
        $input->SetTrade_type("JSAPI");
        //由小程序端传给后端或者后端自己获取
        $input->SetOpenid($openid);
        //向微信统一下单，并返回order，它是一个array数组
        $order = \WxPayApi::unifiedOrder(new \WxPayConfig(), $input);

        //获取userId
        $user = M('user')->where(['openid' => $openid])->find();
        //将订单数据写入数据库
        $insertData['user_id']      = $user['id'];
        $insertData['openid']       = $openid;
        $insertData['out_trade_no'] = $tradeNo;
        $insertData['total_fee']    = $totalFee;
        $insertData['prepayid']     = $order['prepay_id'];
        $insertData['pay_type']    = $payType;
        $insertData['temp_id']     = $tempId;
        $insertData['pay_status']  = 0; //0 未支付
        $insertData['create_time'] = time();
        //$insertData['transaction_id'] = '';//回调会生成的一个id
        //$insertData['commit_time'] = '';

        $rs = M('payorder')->add($insertData);
        if (!$rs) {
            throw new \WxPayException("插入订单表数据异常！");
        }

        //json化返回给小程序端
        header("Content-Type: application/json");
        echo $this->getJsApiParameters($order);
    }

    private function getJsApiParameters($UnifiedOrderResult)
    {
        log::write('统一下单返回数据1：' . json_encode($UnifiedOrderResult), "test");
        //判断是否统一下单返回了prepay_id
        if (!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == "") {
            throw new \WxPayException("参数错误");
        }
        $jsapi = new \WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(\WxPayApi::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
        $jsapi->SetSignType("MD5");
        $jsapi->SetPaySign($jsapi->MakeSign(new \WxPayConfig()));
        $parameters = json_encode($jsapi->GetValues());
        log::write('统一下单返回数据2：' . $parameters, "test");
        return $parameters;
    }

    /**
     * 回调
     * @return [type] [description]
     */
    public function notify()
    {
        $xml = $_REQUEST;
        if ($xml == null) {
            $xml = file_get_contents("php://input");
        }
        if ($xml == null) {
            $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        }

        try {
            Log::write('@@@异步回调数据：' . $xml, 'test');
            $obj       = simplexml_load_string($xml, null, LIBXML_NOCDATA);
            $post_data = object_to_array($obj);
            //$postSign  = $post_data['sign']; //签名
            //unset($post_data['sign']);
            //ksort($post_data); // 对数据进行排序
            //$str         = $this->ToUrlParams($post_data); //对数组数据拼接成key=value字符串
            //$user_sign   = strtoupper(md5($post_data)); //再次生成签名，与$postSign比较

            if (!empty($post_data)) {
                if ($post_data['return_code'] == 'SUCCESS' && $post_data['sign']) {
                    //查询订单是否已经生成
                    $result = M('payorder')->where(['out_trade_no' => $post_data['out_trade_no']])->find();
                    if ($result) {
                        //更新订单状态
                        M('payorder')->where(['out_trade_no' => $post_data['out_trade_no']])->save(['pay_status' => 1, 'commit_time' => time(), 'transaction_id' => $post_data['transaction_id']]);
                    } else {
                        Log::write('@@@没有查询到订单');
                        echo '微信支付失败，数据库未存在该订单。';
                    }
                } else {
                    Log::write('@@@回调失败，错误码：' . $post_data['return_code']);
                    echo '微信支付失败';
                }
            } else {
                Log::write('@@@回调数据异常');
                echo '回调数据异常';
            }
        } catch (\Exception $e) {
            Log::write('@@@微信支付回调抛出异常' . $e->getMessage(), 'test');
            echo '微信支付回调抛出异常' . $e->getMessage();
        }
        //$notify = new \PayNotifyCallBack();
        //$notify->Handle(new \WxPayConfig(), false);
    }
}
